from flask import session
from wtforms.fields.simple import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length
from flask_wtf import FlaskForm
from models import User, Prove, insert

class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[
        DataRequired(message="用户名不能为空"),
        Length(min=6, message="用户名必须至少6位")
    ])

    password = PasswordField('密码', validators=[
        DataRequired(message="密码不能为空"),
        Length(min=8, message="密码必须至少8位")
    ])

    sub_login=SubmitField('登录')
    sub_register = SubmitField('注册')


def is_login(form:LoginForm):
    return form.sub_login.data and form.validate_on_submit()

def is_register(form:LoginForm):
    return form.sub_register.data and form.validate_on_submit()

def submit_login(form:LoginForm):
    if is_login(form):
        username = form.username.data
        password = form.password.data
        if User.validate_user(username, password):
            session['uid'] = User.get_by_username(username).id
            return True
    return False

def submit_register(form:LoginForm):
    if is_register(form):
        username = form.username.data
        password = form.password.data
        if User.register_user(username, password):
            return True
    return False
